<script setup>
import {defineProps, defineEmits, ref} from 'vue';
import axios from "axios";
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";
import {userStore} from '@/store/index.js'

const userItemStore = userStore();

const props = defineProps({
  carList: {
    type: Array,
    required: true,
  },
  currentPage: {
    type: Number,
    required: true,
  },
  pageSize: {
    type: Number,
    required: true,
  },
  totalItems: {
    type: Number,
    required: true,
  }
});

const emit = defineEmits();
const addedToCompare = ref(new Set());
const loadingStates = ref({}); // 用于跟踪每个车辆的加载状态

const handleCurrentChange = (pageNum) => {
  emit('change-page', pageNum);
};

const calculateMonthlyPayment = (price) => {
  const interestRate = 0.05;
  const months = 120;
  const monthlyRate = interestRate / 12;
  const monthlyPayment = (price * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months));
  return monthlyPayment > 0 ? monthlyPayment.toFixed(2) : '0.00';
};

const addToCompare = async (productId) => {
  if (userItemStore.loggedIn) {
    if (loadingStates.value[productId]) return; // 如果正在加载，则不再执行
    loadingStates.value[productId] = true; // 设置为加载状态

    try {
      const checkResponse = await axios.post(`/car/checkCompare/${productId}`);
      if (checkResponse.data) {
        ElMessage.warning("该车辆已在对比列表中");
        return;
      }
      await axios.post(`/car/${productId}`);
      addedToCompare.value.add(productId);
      ElMessage.success("成功添加到对比页面");
    } catch (error) {
      const message = error.response?.data || '添加失败，请重试';
      ElMessage.info(message);
    } finally {
      setTimeout(() => {
        loadingStates.value[productId] = false; // 2秒后重置加载状态
      }, 2000);
    }
  }
  else {
    await router.push({name: 'login'});
    ElMessage.warning('请先登录');
  }
}

const checkLoginAndNavigate=(routeName, productId)=> {
  if (userItemStore.loggedIn) {
    router.push({ name: routeName, params: { id: productId } });
  } else {
    router.push({ name: 'login' });
    ElMessage.warning('请先登录')
  }
}

</script>

<template>
  <div class="car-list">
    <el-row :gutter="20">
      <el-col v-for="car in carList" :key="car.productId" :span="24">
        <div class="car-card">
          <div class="car-left">
            <img :src="$urlImage + car.imgs" alt="车图片" class="car-image"/>
            <div class="car-name-price">
              <h3>{{ car.name }}</h3>
              <p>价格: ¥{{ car.price }}起</p>
              <p>月付：¥{{ calculateMonthlyPayment(car.price) }}起
                <el-popover
                    placement="top-start"
                    :width="300"
                    trigger="hover"
                    content="注:月付是以10年期，年化率5%的月付利息，不包含首付款和保险费用。">
                  <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
                  </template>
                </el-popover>
              </p>
              <el-button type="primary" size="default" @click="router.push({ name: 'carDetails', params: { id: car.productId } })">了解详情</el-button>
              <el-button type="primary" size="default" @click="checkLoginAndNavigate('reservation', car.productId)">预约试驾</el-button>

            </div>
          </div>
          <div class="car-right">
            <p style="text-align: center;">推荐配置
              <el-popover
                  placement="top-start"
                  :width="280"
                  trigger="hover"
                  content="其中加速度：0-100公里/小时(秒)">
                <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
                </template>
              </el-popover>
            </p>
            <el-table :data="[car]" border>
              <el-table-column label="油耗(L/每100公里)" prop="fuelConsumption" width="180px"></el-table-column>
              <el-table-column label="能源" prop="energy" width="100px"></el-table-column>
              <el-table-column label="最高速度(公里/小时)" prop="maxSpeed" width="180px"></el-table-column>
              <el-table-column label="加速度" prop="acceleration" width="80px"></el-table-column>
              <el-table-column label="座位数" prop="seatCount" width="80px"></el-table-column>
              <el-table-column label="月付" prop="price" width="120px">
                ¥{{ calculateMonthlyPayment(car.price) }}起
              </el-table-column>
            </el-table>
          </div>
          <el-button class="add-btn"
                     type="primary"
                     size="default"
                     @click="addToCompare(car.productId)"
                     :disabled="loadingStates[car.productId]">
            <el-popover
                placement="top-start"
                :width="280"
                trigger="hover"
                content="添加到车辆对比列表">
              <template #reference>
                <span style="cursor: pointer; font-size: 20px; font-weight: bold;">+</span>
              </template>
            </el-popover>
          </el-button>
        </div>
      </el-col>
    </el-row>


    <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        layout="total, prev, pager, next, jumper">
    </el-pagination>
  </div>
</template>

<style scoped>
.add-btn {
  position: absolute; /* 使用绝对定位 */
  top: 10px; /* 距离上边10px */
  right: 10px; /* 距离右边10px */
  width: 30px; /* 方形按钮宽度 */
  height: 30px; /* 方形按钮高度 */
  background-color: blue; /* 背景颜色为蓝色 */
  color: white; /* 按钮文字颜色为白色 */
  border: none; /* 无边框 */
  font-size: 18px; /* 字体大小 */
  display: flex; /* 使用 flex 来居中显示文字 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  cursor: pointer; /* 鼠标悬停样式 */
  border-radius: 5px; /* 可选的圆角效果，去除则为直角 */
}
.car-list {
  margin-top: 20px;
}

.car-card {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #070505;
  border-radius: 5px;
  position: relative; /* 为了让按钮浮动在卡片上方 */
}

.car-left {
  flex: 0 0 30%;
  text-align: center;
}

.car-right {
  flex: 0 0 60%;
  padding-left: 40px;
}


.car-image {
  width: 100%;
  height: auto;
}

.car-name-price {
  margin-top: 10px;
}

.car-info {
  padding: 10px;
}
</style>
